<template>
  <div
    class='template-edit-wrapper'
    v-loading='fullscreenLoading'
    element-loading-text="拼命加载中">
    <div class='template-edit-header'>
      <el-button type='primary' @click="$router.back(-1)">返回</el-button>
      <div class='template-edit-header-text'>模板编辑</div>
      <el-button type='warning' @click='savaTemplate'>保存</el-button>
    </div>
    <div class="tool-Container">
      <el-card class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span class='title'><i class='el-icon-thumb'/>问卷组件</span>
        </div>
        <draggable
          v-model='tools'
          :group="{name:'componentsGroup',pull:'clone',put:false}"
          animation="300"
          :sort="false"

          @end='ended'
        >
          <transition-group>
            <div class='dragItem'
                 v-for="(tool,index) in tools"
                 :key="index"
                 @click='addComponent(tool)'>
              {{tool.__config__.label}}</div>
          </transition-group>
        </draggable>

      </el-card>
    </div>
    <div class="p-view">
      <el-card class="box-card" shadow='hover' :body-style="{height:'100%'}">
        <el-form class='drawArea' v-model='formData'
                 :label-position='formConf.labelPosition'
                 :size="formConf.size"
                 :disabled="formConf.disabled"
                 :label-width="formConf.labelWidth + 'px'">
          <el-scrollbar class="right-scrollbar">
            <div class=' form-title' @click='activeFormItem(undefined)'>
              <el-form-item>
                <input class='form-t' type='text' v-model='projectName' :placeholder='formConf.title' @blur='saveProjectInfo'/>
              </el-form-item>
              <el-form-item>
                <el-input class='form-d' rows=2 type='textarea' v-model='projectDescribe' placeholder='问卷描述' resize='none' size='big'  autosize  @blur='saveProjectInfo'></el-input>
              </el-form-item>
            </div>
            <el-divider><i class='el-icon-more'></i></el-divider>
            <draggable
              v-model='drawList'
              group='componentsGroup'
              animation='300'
              :scroll='true'
              @end='itemEnd'
            >
              <DraggableItem class='drawItem'
                             v-for="(item,index) in drawList"
                             :key="item.__config__.renderKey"
                             :currentItem='item'
                             :index='index'
                             :activeId='activeId'
                             :formConf='formConf'
                             :list='drawList'

                             @activeItem='activeFormItem(item)'
                             @copyItem="drawingItemCopy"
                             @deleteItem="drawingItemDelete">
              </DraggableItem>
              <div v-show="!drawList.length" class="empty-info" style='color:#EBAC88;font-size: 18px'>
                从左侧拖入或点选组件进行表单设计
              </div>
            </draggable>
          </el-scrollbar>
        </el-form>
      </el-card>
    </div>
    <div class='right-view'>
      <el-card shadow='hover' >
        <div slot="header" class="clearfix">
          <span class='title'><i class='el-icon-setting'/>配置项</span>
          <span v-if='activeIndex!==0'>--{{activeIndex}}</span>
        </div>
        <right-panel
          :active-data='activeData'
          :active-id='activeId'
          :active-index='activeIndex'

          @data-change='updateProjectItems'
          @modifyTitle='modifyTitle'
        />
      </el-card>
    </div>
  </div>
</template>
<script>
import { formConf,Components } from '@/components/gene/config'
import draggable from 'vuedraggable'
import { deepClone,saveIdGlobal,getIdGlobal } from '@/utils'
import DraggableItem from '@/views/project/form/DraggableItem'
import RightPanel from '@/views/project/form/RightPanel'
import { dbDataConvertForItemJson,formItemConvertData } from '@/utils/convert'
import { debounce,throttle } from 'throttle-debounce'
import { addTemplate, updateTemplate } from '@/api/evaluation/template'
import { delItem } from '@/api/evaluation/templateItem'
let tempActiveData
let idGlobal

export default {
  components: {
    RightPanel,
    draggable,
    // eslint-disable-next-line vue/no-unused-components
    DraggableItem
  },
  // props: ['projectKey'] ,
  data() {
    return {
      idGlobal: getIdGlobal,
      formData: {},
      tools: Components,
      formConf: formConf,
      activeData: {},
      activeId: 0,
      activeIndex: 0,
      projectName: '',
      projectDescribe: '',
      drawList: [],
      isCreate: false,
      fullscreenLoading: true,
      saveIdGlobalDebounce: debounce(340,saveIdGlobal),
      projectKey: '',
      projectTemplate: {
        projectName: '模板',
        projectDescribe: '这是一个新建的模板'
      }
    }
  },
  created () {
    this.projectKey = this.$route.query.projectKey
  },
  async mounted() {
   // await addTemplate({ projectName: formConf.title,projectDescribe: formConf.description }).then(res => {
   //    console.log('templateKey', res)
   //    this.projectKey = res.data
   //  })
    // 深拷贝初始化formconf对象
    if (this.isCreate)
      // 若是新创建的
    {this.formConf = JSON.parse(JSON.stringify(formConf))} else {
      await this.getInfoByKey()
      await this.getProjectItems()
      this.changeToTitle()
      console.log('mounted-drawList',this.drawList)
    }

  },
  watch: {
    drawList: {
      handler(val) {
        console.log('changed!',val)
        this.$nextTick();
      },
      deep: true
    },
    idGlobal: {
      handler(val) {
        if (val) {
          this.saveIdGlobalDebounce(val,this.projectKey)
        }
      }
    }
  },
  methods: {
    savaTemplate() {
      this.$message.success('保存成功啦')
      this.$router.go(-1)
    },
     // 节流
    // 保存项目信息
    saveProjectInfo: debounce(500,false,function() {
      const _this = this
      // console.log(this)
      updateTemplate(JSON.stringify({
        projectName: _this.projectName,
        projectDescribe: _this.projectDescribe,
        projectKey: _this.projectKey
      }))
      // _this.$http.post('/template/update',JSON.stringify({
      //   projectName: _this.projectName,
      //   projectDescribe: _this.projectDescribe,
      //   projectKey: _this.projectKey
      // }))
    }),
    async getInfoByKey() {
      console.log('key', this.projectKey)
      const { data: res } = await this.$http.get('/template/preview/' + this.projectKey)
      const _this = this
      if (res.code !== 200) {
        const timer = setTimeout(() => {
          _this.fullscreenLoading = false
        },500)
        this.$message.error('获取模板头部信息失败')
      } else {
        const timer = setTimeout(() => {
          _this.fullscreenLoading = false
        },500)
        this.$message.success('获取模板头部信息成功')
        this.projectName = res.data.userProject.projectName
        this.projectDescribe = res.data.userProject.projectDescribe
      }
    },
    changeToTitle() {
      this.activeData = {
        name: this.projectName,
        des: this.projectDescribe
      }
      this.activeId = 0
    },
    modifyTitle(detail) {
      this.projectName = detail.name
      this.projectDescribe = detail.des
      this.saveProjectInfo()
    },
    ended(e) {
      //将当前活动设为drawlist中新index的索引
      this.activeFormItem(this.drawList[e.newIndex])
      this.saveProjectItems(this.drawList[e.newIndex])
    },
    //添加左边的组件信息到drawList中
    addComponent(item) {
      const clone = this.cloneComponent(item)
      console.log(clone)
      this.drawList.push(clone)
      this.saveProjectItems(clone)
      this.activeFormItem(clone)
    },
    cloneComponent(origin) {
      const clone = deepClone(origin)
      const config = clone.__config__
      config.span = this.formConf.span // 生成代码时，会根据span做精简判断
      this.createIdAndKey(clone)
      clone.placeholder !== undefined && (clone.placeholder += config.label)
      tempActiveData = clone
      return tempActiveData
    },
    createIdAndKey(item) {
      const config = item.__config__
      // config.formId = ++this.idGlobal
      console.log('formID',config.formId)
      config.renderKey = `${config.formId}${+new Date()}` // 改变renderKey后可以实现强制更新组件
      item.__vModel__ = `field${this.idGlobal}`
      if (Array.isArray(config.children)) {
        config.children = config.children.map(childItem => this.createIdAndKey(childItem))
      }
      return item
    },
    //记录当前活跃项,将其赋值给activeData和activeId
    activeFormItem(currentItem) {
      if (currentItem !== undefined) {
        this.activeData = currentItem
        this.activeId = currentItem.__config__.formId
        this.activeIndex = this.drawList.indexOf(currentItem) + 1
      } else {
        this.changeToTitle()
      }
    },

    drawingItemCopy(item, list) {
      let clone = deepClone(item)
      clone = this.createIdAndKey(clone)
      console.log('clone',clone)
      clone.__config__.formId = undefined
      list.push(clone)
      this.saveProjectItems(clone)
      this.activeFormItem(clone)

    },
    drawingItemDelete(index, list) {
      const item = list[index]
      list.splice(index, 1)
      this.$nextTick(() => {
        const len = this.drawList.length
        if (len) {
          this.activeFormItem(this.drawList[len - 1])
        }
      })
      this.deleteProjectItems(item)
    },
    async getProjectItems() {
      const { data: res } = await this.$http.get('/template/item/list/' + this.projectKey)

      // 添加转换后的表单可用的数据到drawList中
      res.data.forEach(item => {
        this.drawList.push(dbDataConvertForItemJson(item))
      })
    },

    async saveProjectItems(item) {
      const params = formItemConvertData(item,this.projectKey)
      const { data: res } = await this.$http.post('/template/item', params)
      if (res.code === 200) {
        this.$message.success('保存问题 ' + item.__config__.label + ' 成功')
        item.__config__.formId = res.data
        console.log('保存问题 ', res)
      }
    },
    updateProjectItems(item) {
      console.log('update-item------item.typeId', item.typeId)
      const params = formItemConvertData(item, this.projectKey)
      this.$http.put('/template/item', params).then(res => {
        console.log(res)
        if(res.data.code === 200) this.$message.success('修改问题 ' + item.__config__.label + ' 成功')
      })
    },
    deleteProjectItems(item) {
      if (item.__config__.formId) {
        delItem(item.__config__.formId).then(res => {
          if(res.code === 200) {
            this.$message.success('删除问题 ' + item.__config__.label + ' 成功')
          }
        })
      }

    },
    //拖动后排序
    async itemEnd(e) {
      const params = { projectKey: this.projectKey }
      this.activeFormItem(this.drawList[e.newIndex])
      params.id = this.drawList[e.newIndex].__config__.formId
      if (this.drawList[e.newIndex - 1]) {
        params.beforePosition = this.drawList[e.newIndex - 1].sort
      }
      if (this.drawList[e.newIndex + 1]) {
        params.afterPosition = this.drawList[e.newIndex + 1].sort
      }
      console.log('sort',params)
      const { data: res } = await this.$http.post('/template/item/sort',params)
      if (res.code === 200) {
        this.$message.info('sort')
      }
    }
  }


}
</script>
<style lang="less" scoped>
@import "/src/assets/css/scroll.css";
@import "src/assets/css/themeColor";
.template-edit-wrapper {
  width: 100%;
  height: 100%;
  background-color: #f1f1f3;
}
.template-edit-header {
  display: flex;
  margin-right: 50px;
  padding: 0 20px;
  align-items: center;
  justify-content: space-between;
  width: 97%;
  background-color: #fdfdfd;
  height: 65px;
}
.template-edit-header-text {
  font-size: 24px;
  color: #ea9e9e;
}
.el-card {
  height:100%;
  min-height: 200px;
  border-radius: 10px;
  text-align: center;
}
.tool-Container {
  box-sizing: border-box;
  height: 100%;
  width: 20%;
  float: left;
  padding: 15px;
  .el-card {
    overflow-y: auto;
    overflow-x: hidden;

    .title{
      font-size: 18px;
      letter-spacing: 10px;
    }
    .dragItem {
      box-sizing: border-box;
      text-align: center;
      font-size: 14px;
      width: calc(50% - 4px);
      float: left;
      padding: 10% 0;
      border: 2px transparent dashed;
      transition: 0.5s ease-out;

    }
    .dragItem:hover{
      border:@theme_pink 2px dashed;
    }
  }
}
.p-view {
  box-sizing: border-box;
  height: 100%;
  width: 60%;
  float: left;
  padding: 15px;
  .el-card {
    .drawArea{
      height: 90%;
      overflow-y: auto;
      overflow-x: hidden;
    }
    /deep/.drawItem{
      text-align: left;
      min-height: 125px;
      box-sizing: border-box;
      width: 100%;
      overflow: hidden;
      padding: 10px;
      cursor:move;
      border: #ddd 1px dashed;
      border-top: none;
      &:first-child{
        border: #ddd 1px dashed;
      }
    }
    /deep/.drawing-item-delete,/deep/.drawing-item-copy{
      cursor: pointer;
    }
    .form-title{
      box-sizing: border-box;
      height: 150px;
      padding: 10px;
      .el-form-item{
        display: flex;
        align-items: center;
        justify-content: center;
      }
      input{
        display: block;
        text-align: center;
        border:none;
        outline:transparent;
        transition:outline-color .2s;
      }
      input:focus{
        outline: @theme_pink 2px dashed;
      }
      .form-t{
        height: 30px;
        font-weight: 600;
        font-size:20px;
      }
      .form-d{
        width: 600px;
      }
    }
  }
}
.right-view{
  box-sizing: border-box;
  height: 100%;
  width:20% ;
  float: left;
  padding: 15px;
  .title{
    font-size: 18px;
    //font-weight: 600;
    letter-spacing: 10px;
    text-align: center;
  }
  .el-card{
    overflow-y: auto;
    overflow-x: hidden;
  }
}
.activeItem{
  box-sizing: border-box;
  border: @theme_pink 1px solid;
}
.right-scrollbar {
  .el-scrollbar__view {
    padding: 12px 18px 15px 15px;
  }
}



</style>
